package rabbitmq.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;

@RestController
@RequestMapping("/dev")
public class DevController{
    private  Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        /**
         * 只确认消息是否到达exchange
         * 一般是exchange 不存在
         */
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if(ack){
                log.info("消息发送-success:correlationData({}),ack({}),cause({})",correlationData,ack,cause);
            }else{
                log.info("消息发送-error:correlationData({}),ack({}),cause({})",correlationData,ack,cause);
            }
        });
        /**
         *  ReturnCallback消息没有正确到达队列时触发回调，如果正确到达队列不执行
         *  一般是队列不存在
          */
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                log.info("消息发送-exception:message({}),replyCode({}),replyText({}),exchange({}),routingKey({})",message,replyCode,replyText,exchange,routingKey);
            }
        });
    }



    /**
     * 可靠性投递
     * producer--->rabbitmq broker--->exchange--->queue--->consumer
     * 消息从 producer 到 exchange 则会返回一个 confirmCallback 。
     * 消息从 exchange-->queue 投递失败则会返回一个 returnCallback 。
     */
    @RequestMapping("/mq")
    public String mq(String msg){
        rabbitTemplate.convertAndSend("hello", "hello" +msg);
        return "mq";
    }

    @RequestMapping("/direct")
    public String direct(String msg){
         rabbitTemplate.convertAndSend("direct.exchange","routingKey.direct", "direct.exchange"+msg);
         rabbitTemplate.convertAndSend("direct.exchange","routingKey.direct2", "direct.exchange2"+msg);
        return "mq";
    }
    @RequestMapping("/fanout")
    public String fanout(String msg){
        rabbitTemplate.convertAndSend("fanout.exchange","", "fanout.exchange"+msg);
        return "mq";
    }

    @RequestMapping("/timeout")
    public String timeout(String msg){
        /**
         * 配置参考 DelayQueueConfig.java
         */
        rabbitTemplate.convertAndSend("delay.queue", msg);
        return "mq";
    }

}
